﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using EDiamondModel;

public partial class Pages_GioHang : System.Web.UI.Page
{
    private int mSTT;
    static string prevPage = string.Empty;
    public int Tinh_STT()
    {
        mSTT += 1;
        return mSTT;
    }
    private void LienKetDuLieu()
    {
        if (Session["GioHang"] == null)
            Session["GioHang"] = new List<MuaSanPham>();
        Ds_giohang.DataSource = (List<MuaSanPham>)Session["GioHang"];
        Ds_giohang.DataBind();
    }
    protected void Page_Load(object sender, EventArgs e)
    {

        if (Request["Loi"] != null)
            Loi.Text = Request["Loi"].ToString();
        if (!IsPostBack)
        {
            double sl = GioHang.TongSanpham();
            double tg = GioHang.TongTrigia();
            Label SLuong = this.Page.Master.FindControl("SLuong") as Label;
            SLuong.Text = "<b>" + sl.ToString() + "<b>";
            Label TGia = this.Page.Master.FindControl("TGia") as Label;
            TGia.Text = "<b>" + tg.ToString() + "<b>";
            EDiamondEntities1 d = new EDiamondEntities1();
            LienKetDuLieu();
            //rdbHinhThucVanChuyen.DataSource = d.HinhThucVanChuyens;
            if (rdbHinhThucVanChuyen.Items != null && rdbHinhThucVanChuyen.Items.Count > 0)
            {
                rdbHinhThucVanChuyen.Items.Clear();
            }
            foreach (var item in d.HinhThucVanChuyens)
            {
                ListItem li = new ListItem(item.Ten, item.KyHieu);
                li.Attributes.Add("onclick", "javascript:ShowExt('" + li.Value + "')");
                rdbHinhThucVanChuyen.Items.Add(li);
            }
            rdbHinhThucVanChuyen.SelectedIndex = 0;
            rdbHinhThucVanChuyen.DataBind();
            var x = d.Nuocs;
            ddlQuocGia.DataSource = d.Nuocs;
            ddlQuocGia.DataBind();
            if (x.Count() > 0)
            {
                int value = x.First().Id;
                ddlThanhPho.DataSource = d.ThanhPhoes.Where(b => b.IdNuoc == value);
                ddlThanhPho.DataBind();
                List<MuaSanPham> ds = GioHang.NhanGiohang();
                double TongTrongLuong = 0;
                DichVuVanChuyen v = new DichVuVanChuyen();
                foreach (MuaSanPham s in ds)
                {
                    SanPham sp = d.SanPhams.Single(b => b.SanPhamID == s.SanPhamID);
                    TongTrongLuong += sp.TrongLuong.HasValue ? sp.TrongLuong.Value : 0;
                }
                TongTrongLuong = 1;
                lbGiaVC.Text = v.LayGiaVanChuyen((float)TongTrongLuong, -1, value).ToString();
            }
            //prevPage = Request.UrlReferrer.ToString();
        }
    }
    protected void ddlQuocGiaSelectedIndexChange(object sender, EventArgs e)
    {
        if (ddlQuocGia.SelectedIndex != -1)
        {
            EDiamondEntities1 d = new EDiamondEntities1();
            int value = int.Parse(ddlQuocGia.SelectedValue);
            IQueryable<ThanhPho> dx = d.ThanhPhoes.Where(x => x.IdNuoc == value);
            ddlThanhPho.DataSource = dx;
            ddlThanhPho.DataBind();
            DichVuVanChuyen v = new DichVuVanChuyen();
            if (dx.Count()>0)
            {
                List<MuaSanPham> ds = GioHang.NhanGiohang();
                double TongTrongLuong = 0;
                foreach (MuaSanPham s in ds)
                {
                    SanPham sp = d.SanPhams.Single(x => x.SanPhamID == s.SanPhamID);
                    TongTrongLuong += sp.TrongLuong.HasValue ? sp.TrongLuong.Value : 0;
                }
                TongTrongLuong = 1;
                lbGiaVC.Text = v.LayGiaVanChuyen((float)TongTrongLuong, -1, dx.First().Id).ToString();
            }
        }
        else
        {
            ddlThanhPho.DataSource = new EDiamondModel.ThanhPho();
            ddlThanhPho.DataBind();
        }
    }
    protected void ddlThanhPhoSelectedIndexChange(object sender, EventArgs e)
    {
        if (ddlThanhPho.SelectedIndex != -1)
        {
            DichVuVanChuyen v = new DichVuVanChuyen();
            EDiamondEntities1 d = new EDiamondEntities1();
            List<MuaSanPham> ds = GioHang.NhanGiohang();
            double TongTrongLuong = 0;
            foreach (MuaSanPham s in ds)
            {
                SanPham sp = d.SanPhams.Single(x => x.SanPhamID == s.SanPhamID);
                TongTrongLuong += sp.TrongLuong.HasValue ? sp.TrongLuong.Value : 0;
            }
            TongTrongLuong = 1;
            lbGiaVC.Text = v.LayGiaVanChuyen((float)TongTrongLuong, -1, int.Parse(ddlThanhPho.SelectedValue)).ToString();
        }
    }
    protected void Ds_giohang_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Footer)
        {
            double atm = GioHang.TongTrigia();
            e.Row.Cells[4].Text = atm.ToString("#,###");
            Session["payment_amt"] = atm;
        }
    }
    protected void Ds_giohang_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        Ds_giohang.EditIndex = -1;
        LienKetDuLieu();
    }
    protected void Ds_giohang_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        GioHang.XoaSp(e.RowIndex);
        LienKetDuLieu();
    }
    protected void Ds_giohang_RowEditing(object sender, GridViewEditEventArgs e)
    {
        Ds_giohang.EditIndex = e.NewEditIndex;
        LienKetDuLieu();
    }
    protected void Ds_giohang_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        List<MuaSanPham> gio = (List<MuaSanPham>)Session["GioHang"];
        string sl = ((TextBox)Ds_giohang.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
        MuaSanPham sp = (MuaSanPham)gio[e.RowIndex];
        GioHang.CapnhatSoluong(sp, int.Parse(sl));
        Ds_giohang.EditIndex = -1;
        LienKetDuLieu();
    }
    protected void CapNhat_Click(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty((string)Session["Madn"]))
        {
            //ThongBao.Text = GioHang.CapNhatGioHang();
            LienKetDuLieu();
        }
        else
        {
            //ThongBao.Text = "Quý khách chưa đăng nhập, vui lòng đăng nhập để thực hiện chức năng này.";
        }
    }
    private bool Check(bool TT)
    {

        if (Session["Madn"] == null || Session["Madn"].ToString() == "")
        {
            Response.Redirect("~/Pages/GioHang.aspx?Loi=Vui lòng đăng nhập");
            return false;
        }

        EDiamondEntities1 d = new EDiamondEntities1();
        string htvc = rdbHinhThucVanChuyen.SelectedItem.Value;

        Session["IdHinhThucVanChuyen"] = d.HinhThucVanChuyens.Single(x => x.KyHieu == htvc).Id;

        if (htvc == "DV")
        {
            if (ddlQuocGia.SelectedIndex == -1 || ddlThanhPho.SelectedIndex == -1 || txtDiaChi.Text == "")
            {
                Response.Redirect("~/Pages/GioHang.aspx?Loi=Nhập đầy đủ thông tin giao hàng");
                return false;
            }
            Session["Nuoc"] = ddlQuocGia.SelectedValue;
            Session["ThanhPho"] = ddlThanhPho.SelectedValue;
            Session["DiaChi"] = txtDiaChi.Text;

        }
        else
        {
            Session["Nuoc"] = "-1";
            Session["ThanhPho"] = "-1";
            Session["DiaChi"] = "";
        }

        if (TT == true)
        {
            if (rdbHinhThucVanChuyen.SelectedValue == "DV")
            {
                DichVuVanChuyen v = new DichVuVanChuyen();
                
                List<MuaSanPham> ds = GioHang.NhanGiohang();
                double TongTrongLuong = 0;
                foreach (MuaSanPham s in ds)
                {
                    SanPham sp = d.SanPhams.Single(x => x.SanPhamID == s.SanPhamID);
                    TongTrongLuong += sp.TrongLuong.HasValue ? sp.TrongLuong.Value : 0;
                }
                TongTrongLuong = 1;
                Session["giavanchuyen"] =
                    double.Parse(v.LayGiaVanChuyen(
                        int.Parse(TongTrongLuong.ToString()), -1, 
                        int.Parse(ddlThanhPho.SelectedValue))
                        .ToString());

            }
            Response.Redirect("~/Pages/CheckoutReview.aspx?TT=1");
            return true;
        }
        return true;
    }
    protected void lbtTT_Click(object sender, EventArgs e)
    {
        Check(true);
    }
    protected void CheckoutBtn_Click(object sender, EventArgs e)
    {
        if (!Check(false)) return;

        NVPAPICaller payPalCaller = new NVPAPICaller();
        string retMsg = "";
        string token = "";
        if (rdbHinhThucVanChuyen.SelectedValue == "DV")
        {
            DichVuVanChuyen v = new DichVuVanChuyen();
            EDiamondEntities1 d = new EDiamondEntities1();
            List<MuaSanPham> ds = GioHang.NhanGiohang();
            double TongTrongLuong = 0;
            foreach (MuaSanPham s in ds)
            {
                SanPham sp = d.SanPhams.Single(x => x.SanPhamID == s.SanPhamID);
                TongTrongLuong += sp.TrongLuong.HasValue ? sp.TrongLuong.Value : 0;
            }
            TongTrongLuong = 1;
            Session["giavanchuyen"] =
                    double.Parse(v.LayGiaVanChuyen(
                        int.Parse(TongTrongLuong.ToString()), -1,
                        int.Parse(ddlThanhPho.SelectedValue))
                        .ToString());

        }
        string amt = Session["payment_amt"].ToString();
        bool ret = payPalCaller.ShortcutExpressCheckout(amt, ref token, ref retMsg);
        if (ret)
        {
            Session["token"] = token;
            Response.Redirect(retMsg);
        }
        else
        {
            Response.Redirect("CheckoutError.aspx?" + retMsg);
        }
    }
}